package es.mahulo.battleship.resource;

import java.util.List;
import java.util.logging.Logger;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import es.mahulo.battleship.api.service.GameService;
import es.mahulo.battleship.model.ArrayShip;
import es.mahulo.battleship.model.Game;
import es.mahulo.battleship.model.Hit;
import es.mahulo.battleship.model.Shot;

@Component
@Path("battleship")
public class GameResource {
	Logger  logger = Logger.getLogger(GameResource.class.getName());
	
	private GameService gameService;
	
	@Autowired
	public void setGameService(GameService gameService) {
		this.gameService = gameService;
	}
	
	@GET
	@Path("list")
	@Produces("application/json")
	public List<Game> getGames(@Context SecurityContext sc) {
		logger.info("getGames " + sc.getUserPrincipal().getName());
		
		return gameService.getAllFromUser(sc.getUserPrincipal().getName());
	}

	
	@GET
	@Path("new")
	@Produces("application/json")
	public Game newGame(@Context SecurityContext sc) throws Exception {
		logger.info("Create game " + sc.getUserPrincipal().getName());
		
		return gameService.startUp(sc.getUserPrincipal().getName());
	}
	
	


	@GET
	@Path("join/{gameId}")
	@Produces("application/json")
	public Game joinGame(@Context SecurityContext sc,@PathParam("gameId") Long  gameId)  throws Exception {
		logger.info("joinPlayer " + " " + gameId + " " +sc.getUserPrincipal().getName());
		
		return gameService.joinPlayer(gameId,sc.getUserPrincipal().getName());
	}

	
	@POST
	@Path("addships/{gameId}")
	@Consumes("application/json")
	public void addShips(@Context SecurityContext sc,@PathParam("gameId") Long  gameId, ArrayShip ships) throws Exception {
		logger.info("Add Ship " + gameId + " " + sc.getUserPrincipal().getName() + " " + ships);
		
		gameService.addShip(gameId,sc.getUserPrincipal().getName(),ships.getShips());
	}
	
	
	@POST
	@Path("shot/{gameId}")
	@Consumes("application/json")
	@Produces("application/json")
	public Hit shot(@Context SecurityContext sc, @PathParam("gameId") Long  gameId,Shot shot) throws Exception {
		
		logger.info("Shot " + gameId + " " + sc.getUserPrincipal().getName() + " " + shot);
		
		Boolean isHit = gameService.shot(gameId,sc.getUserPrincipal().getName(), shot);
		
		Hit hit = new Hit();
		hit.setHit(isHit);
		
		return hit;
	}
}
